<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #avatar>
        <MultiImageUpload
          v-model="formData.imgList1"
          :limit="1"
          @update:model-value="(val) => changeOneImg(val, formData, 'avatar')"
        />
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import {
  getCustomerList,
  getDeptList,
  getDeptRoleList,
  getOrganizationList,
  getUserList,
} from "@/commonData";
import { phoneRules } from "@/commonData/rules";
import { accountTypeList, enableList, genderList, userTypeList } from "@/commonData/dict";
import { changeOneImg } from "@/utils/changeData";
import { createInputList } from "@/utils/form";
import InvoiceDeliveryAddressesAPI from "@/api/custom/invoice-delivery-addresses";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const customerList = ref([]);

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  //    customerId*	string
  // 所属客户ID

  const list = createInputList([
    {
      type: "select",
      data: customerList,
      prop: "customerId",
      label: "所属客户",
      attrs: { requiredFlag: true },
    },
    { prop: "recipientAddress", label: "发票邮寄地址", attrs: { requiredFlag: true } },
    { prop: "recipientName", label: "收件人姓名", attrs: { requiredFlag: true } },
    { prop: "recipientPhone", label: "收件人电话", attrs: { requiredFlag: true } },
  ]);

  addProperty(list);
  return list;
};
requestFormOptions.value = createRequestFormOptions();

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();

  getCustomerList(customerList);
  // getOrganizationList(organizationList);
  // getDeptList(deptList);
  // getRoleList(roleList);
  // getUserList(userList);
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await InvoiceDeliveryAddressesAPI.getInfo(id);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await InvoiceDeliveryAddressesAPI.create(data);
      // ElMessage.success("操作成功");
    } else if (formType.value === "update") {
      await InvoiceDeliveryAddressesAPI.update(data.id, data);
      // ElMessage.success("操作成功");
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const getFormData = () => {
  return formData.value;
};
</script>
